package com.zhkj.txg.module.product.vm

import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseApplication
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.module.product.entity.CodeResponse
import com.zhkj.txg.module.product.entity.SaveViewResponse
import com.zhkj.txg.module.product.model.ProductManager
import com.zhkj.txg.utils.ImageUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File


class ShareViewModel(application: Application) : BaseViewModel(application) {

    private val manager = ProductManager()
    val savePictureLiveData = MutableLiveData<List<File>>()
    val qrCodeLiveData = MutableLiveData<HttpResponse<CodeResponse>>()
    val saveViewLiveData = MutableLiveData<SaveViewResponse>()

    /**
     * 将缓存中的图片保存到下载文件夹中
     */
    fun savePicture(context: Context, images: List<String>) {
        val subscribe = Observable.fromIterable(images).map {
            // 缓存中的图片
            val cacheImage = ImageUtils.getCacheImage(context, it)
            // 要复制到的图片
            val root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            val newFile = File(root, "${System.currentTimeMillis()}.jpg")
            cacheImage.copyTo(newFile)
        }.toList().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({ list ->
            // 插入图库
            if (list.isNotEmpty()) list.forEach {
//                MediaStore.Images.Media.insertImage(
//                    BaseApplication.INSTANCE.contentResolver,
//                    it.absolutePath, it.name, null
//                )
                val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                val uri: Uri = Uri.fromFile(it)
                intent.data = uri
                context.sendBroadcast(intent)
            }
            savePictureLiveData.value = list
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }

    /**
     * 将View保存为图片
     */
    fun saveView2Picture(view: View, share2WeChat: Boolean = false) {
        val subscribe = Observable.create<Bitmap> {
            val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.RGB_565).apply {
                view.draw(Canvas(this))
            }
            it.onNext(bitmap)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).subscribe({ bitmap ->
            val file = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "${System.currentTimeMillis()}.jpg"
            )
            file.outputStream().use {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
                bitmap.recycle()
                it.flush()
                // 插入图库
                MediaStore.Images.Media.insertImage(
                    BaseApplication.INSTANCE.contentResolver,
                    file.absolutePath, file.name, null
                )
                saveViewLiveData.postValue(SaveViewResponse(file.path, share2WeChat))
            }
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }

    /**
     * 将View保存为图片
     */
    fun saveView2Picture(list: MutableList<View>) {
        val subscribe = Observable.fromIterable(list).map {
            Bitmap.createBitmap(it.width, it.height, Bitmap.Config.RGB_565).apply {
                it.draw(Canvas(this))
            }
        }.map { bitmap ->
            val file = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                "${System.currentTimeMillis()}.jpg"
            )
            file.outputStream().use {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
                bitmap.recycle()
                it.flush()
            }
            // 插入图库
            MediaStore.Images.Media.insertImage(
                BaseApplication.INSTANCE.contentResolver,
                file.absolutePath, file.name, null
            )
        }.toList().subscribeOn(Schedulers.io()).subscribe({
            saveViewLiveData.postValue(SaveViewResponse(""))
        }, { it.printStackTrace() })
        dispose.add(subscribe)
    }

    /**
     * 生成二维码
     */
    fun getQRCode(goodsId: Long) {
        val listener = ViewModelSubscribeListener(qrCodeLiveData)
        val qrCode = manager.getQrCode(AccountManager.getToken(), goodsId, listener)
        dispose.add(qrCode)
    }
}